package tcpUSClient;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;

import util.SocketManager;

public class UpdateClient {
private SocketManager so;
	
	public UpdateClient(String ip, int port) {
		try {
			so = new SocketManager(ip, port);
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
	
	public boolean validate(String user, String pass) {
		String reply;
		try {
			so.write("USER " + user + "\r\n");
			reply = so.read();
			so.write("PASS " + pass + "\r\n");
			reply = so.read();
			if(reply.startsWith("200")) return true;
		} catch (IOException e) {
			e.printStackTrace();
		}

		return false;
	}
	
	public void getFile()
	{
		try
		{
			so.write("GET_FILE\r\n");
			{
				int filesize=6022386; // filesize temporary hardcoded

			    long start = System.currentTimeMillis();
			    int bytesRead;
			    int current = 0;
			    // localhost for testing
			    Socket sock = new Socket("127.0.0.1",13267);
			    System.out.println("Connecting...");

			    // receive file
			    byte [] mybytearray  = new byte [filesize];
			    InputStream is = so.getSocket().getInputStream();
			    FileOutputStream fos = new FileOutputStream("data/configuration-copy.doc");
			    BufferedOutputStream bos = new BufferedOutputStream(fos);
			    bytesRead = is.read(mybytearray,0,mybytearray.length);
			    current = bytesRead;

			    do {
			       bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
			       if(bytesRead >= 0) current += bytesRead;
			    } while(bytesRead > -1);

			    bos.write(mybytearray, 0 , current);
			    bos.flush();
			    long end = System.currentTimeMillis();
			    System.out.println(end-start);
			    bos.close();
			    sock.close();
			  }
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public boolean quit(){
		try {
			so.write("QUIT\r\n");
			String reply = so.read();
			if (reply.startsWith("203"))
				return true;
		}
		catch (IOException e) {e.printStackTrace();}
		return false;
	}
}
